package com.cbarmstrong.FinanceWeb;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cbarmstrong.Finance.Data;
import com.cbarmstrong.Finance.TradeSet;

/**
 * Servlet implementation class Performance
 */
@WebServlet("/Performance")
public class Performance extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Performance() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection c;
		Statement s1, s2;
		ResultSet r1, r2;
		int id, position, lastPosition=0, count=0, c10=0, c30=0, c90=0;
		long diff;
		String name, table="<TABLE><TR style='background-color: black; color: white; font-weight: bold;'><TD>Stock<TD>10 Day<TD>30 Day<TD>90 Day<TD>All time</TR>";
		double p=0, p10=0, p30=0, p90=0;
		String[] rowStyle={"style='background-color: #eeeeee;'", "style='background-color: #888888'"};
		TradeSet ts, ts10, ts30, ts90;
		Calendar today=Calendar.getInstance(), tradeDay=Calendar.getInstance();
		NumberFormat nf=NumberFormat.getInstance();
		try{
			c=Data.initConnection();
			s1=c.createStatement();
			s2=c.createStatement();
			r1=s1.executeQuery("SELECT id,name FROM stock");
			while(r1.next()){
				id=r1.getInt("id");
				name=r1.getString("name");
				r2=s2.executeQuery("SELECT position, price, date FROM ratios WHERE stockid="+id+" ORDER BY date ASC");
				ts=new TradeSet();
				ts10=new TradeSet();
				ts30=new TradeSet();
				ts90=new TradeSet();
				while(r2.next()){
					position=r2.getInt("position");
					if(r2.isFirst()){ lastPosition=position; }
					tradeDay.setTime(r2.getDate("date"));
					diff=(today.getTimeInMillis()-tradeDay.getTimeInMillis())/1000/60/60/24;
					Data.getLogger().fine("Diff: "+diff+" between "+today.getTime()+" and "+tradeDay.getTime());
					if(position!=lastPosition){
						if(position==0){
							if(!ts.currentlyOut()) ts.closeTrade(r2.getDate("date"), r2.getDouble("price"));
							if(!ts10.currentlyOut()) ts10.closeTrade(r2.getDate("date"), r2.getDouble("price"));
							if(!ts30.currentlyOut()) ts30.closeTrade(r2.getDate("date"), r2.getDouble("price"));
							if(!ts90.currentlyOut()) ts90.closeTrade(r2.getDate("date"), r2.getDouble("price"));
						}
						else{ 
							ts.openTrade(r2.getDate("date"), position, r2.getDouble("price"), 0); 
							if(diff<10) ts10.openTrade(r2.getDate("date"), position, r2.getDouble("price"), 0);
							if(diff<30) ts30.openTrade(r2.getDate("date"), position, r2.getDouble("price"), 0);
							if(diff<90) ts90.openTrade(r2.getDate("date"), position, r2.getDouble("price"), 0);
						}
					}
					lastPosition=position;
				}
				table+="<TR "+rowStyle[(r1.getRow()%2)]+"><TD>"+name+"<TD>"+
						nf.format(ts10.getProfit())+"("+ts10.tradeCount()+")<TD>"+
						nf.format(ts30.getProfit())+"("+ts30.tradeCount()+")<TD>"+
						nf.format(ts90.getProfit())+"("+ts90.tradeCount()+")<TD>"+
						nf.format(ts.getProfit())+"("+ts.tradeCount()+")</TR>";
				count+=ts.tradeCount(); p+=ts.getProfit();
				c10+=ts10.tradeCount(); p10+=ts10.getProfit();
				c30+=ts30.tradeCount(); p30+=ts30.getProfit();
				c90+=ts90.tradeCount(); p90+=ts90.getProfit();
			}
			c.close();
		} catch(Exception e){
			e.printStackTrace();
		}
		table+="<TR><TD>Totals:<TD>"+nf.format(p10)+"("+c10+")<TD>"+
				nf.format(p30)+"("+c30+")<TD>"+
				nf.format(p90)+"("+c90+")<TD>"+
				nf.format(p)+"("+count+")</TR>";
		response.getWriter().write("<HTML><BODY>"+table+"</TABLE></BODY></HTML>");
	}

}
